###########################################################################
#
# Copyright 2016 Realm Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
###########################################################################

find_program(LCOV_PATH lcov)
find_program(GENHTML_PATH genhtml)
find_program(GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/tests)

set(CMAKE_CXX_FLAGS_COVERAGE "-g -O0 -fprofile-arcs -ftest-coverage -DCATCH_CONFIG_FAST_COMPILE")
mark_as_advanced(CMAKE_CXX_FLAGS_COVERAGE)

if(CMAKE_BUILD_TYPE STREQUAL "Coverage")
  if(NOT (LCOV_PATH AND GENHTML_PATH AND GCOVR_PATH))
    message(FATAL_ERROR "Generating a coverage report requires lcov and gcovr")
  endif()

  function(create_coverage_target targetname testrunner)
    add_custom_target(${targetname}
      # Clear previous coverage information
      COMMAND ${LCOV_PATH} --directory . --zerocounters

      # Run the tests
      COMMAND ${testrunner}

      # Generate new coverage report
      COMMAND ${LCOV_PATH} --directory . --capture --output-file coverage.info
      COMMAND ${LCOV_PATH} --extract coverage.info '${CMAKE_SOURCE_DIR}/src/*' --output-file coverage.info.cleaned
      COMMAND ${GENHTML_PATH} -o coverage coverage.info.cleaned
      COMMAND ${CMAKE_COMMAND} -E remove coverage.info coverage.info.cleaned

      COMMAND echo Open coverage/index.html in your browser to view the coverage report.

      WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    )

    add_custom_target(${targetname}-cobertura
      COMMAND ${testrunner}
      COMMAND ${GCOVR_PATH} -x -o coverage.xml -f 'src/.*' -f "${CMAKE_SOURCE_DIR}/src.*" --exclude-directories "${CMAKE_BINARY_DIR}/tests" --exclude-directories="${CMAKE_SOURCE_DIR}/\.tmp" --exclude ".*realm\-core.*" --exclude ".*realm\-sync.*"
      COMMAND echo Code coverage report written to coverage.xml

      WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    )
  endfunction()
else()
  function(create_coverage_target targetname testrunner)
    add_custom_target(${targetname}
      COMMAND echo "Configure with -DCMAKE_BUILD_TYPE=Coverage to generate coverage reports")

    add_custom_target(${targetname}-cobertura
      COMMAND echo "Configure with -DCMAKE_BUILD_TYPE=Coverage to generate coverage reports")
  endfunction()
endif()
